import * as Types from 'containers/ActionTypes';
import * as Helper from 'Helper';
import * as MyWorkService from 'services/MyWorkService';
import * as PublicWorkService from 'services/PublicWorkService';
import Actions from 'containers/Actions';

export function getWorkDetail(workId) {
  return () => PublicWorkService.getWorkById(workId);
}

export function getMyWorkDetail(workId) {
  return (dispatch, getState) => {
    const state = getState();
    const accessToken = Helper.getMyToken(state);

    if (!accessToken) {
      return Promise.reject('Unauthenticated');
    }
    return MyWorkService.getMyWorkDetail(accessToken, workId);
  }
}

export function likeThisWork(workId) {
  return (dispatch, getState) => {
    const state = getState();
    const accessToken = Helper.getMyToken(state);

    if (!accessToken) {
      return Promise.reject('Unauthenticated');
    }
    dispatch({ type: Types.WORK.UPDATE_LIKE_REQUEST });
    return MyWorkService.likeThisWork(accessToken, workId).then(() => {
      dispatch({
        type: Types.WORK.UPDATE_LIKE_SUCCESS,
        workId,
      });
    }, () => {
      dispatch({
        type: Types.WORK.UPDATE_LIKE_FAILED,
        workId,
      });
    });
  };
}

export function unlikeThisWork(workId) {
  return (dispatch, getState) => {
    const state = getState();
    const accessToken = Helper.getMyToken(state);

    if (!accessToken) {
      return Promise.reject('Unauthenticated');
    }
    dispatch({ type: Types.WORK.UPDATE_UNLIKE_REQUEST });
    return MyWorkService.unlikeThisWork(accessToken, workId).then(() => {
      dispatch({
        type: Types.WORK.UPDATE_UNLIKE_SUCCESS,
        workId,
      });
    }, () => {
      dispatch({
        type: Types.WORK.UPDATE_UNLIKE_FAILED,
        workId,
      });
    });
  };
}

export function retrieveLikeStatus(workId) {
  return (dispatch, getState) => {
    const state = getState();
    const accessToken = Helper.getMyToken(state);

    if (!accessToken) {
      return Promise.reject('Unauthenticated');
    }
    return MyWorkService.getMyLikeStatus(accessToken, workId).then(data => data.liked);
  };
}

export function updateMyWorkById(workId, name, title, categoryId, description) {
  return Actions.MyAction.updateWorkDetail(workId, name, title, categoryId, description);
}

export function changeMyWorkStatus(workId, status) {
  return Actions.MyAction.changeWorkStatus(workId, status);
}

export function getRecommendedWorkList(pageId, limit) {
  return () => PublicWorkService.getPublicWorks(pageId, limit, 'LIKE_COUNT', 'DESC')
}

export function getLatestWorkList(pageId, limit) {
  return () => PublicWorkService.getPublicWorks(pageId, limit, 'PUBLISH_TIME', 'DESC')
}

export function getCategoryWorkList(categoryId, pageId, limit) {
  return () => PublicWorkService.getCategoryWorks(categoryId, pageId, limit, 'LIKE_COUNT', 'DESC')
}
